package com.hyacinth.cloudnote.modules.note.service;

import com.hyacinth.cloudnote.common.enums.UserStatus;
import com.hyacinth.cloudnote.common.exception.ExceptionHolder;
import com.hyacinth.cloudnote.modules.note.model.User;
import com.hyacinth.cloudnote.modules.note.repository.UserRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

import static com.hyacinth.cloudnote.modules.common.errorcode.NoteErrorCode.E1000000001;
import static com.hyacinth.cloudnote.modules.common.errorcode.NoteErrorCode.E1000000003;

/**
 * User实体对应的业务逻辑Service实现类
 * @author zhangfb
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public User save(User model) {
        // 校验手机号，唯一非空
        boolean existsMobile;
        if (model.isNew()) {
            existsMobile = userRepository.existsByMobile(model.getMobile());
        } else {
            existsMobile = userRepository.existsByMobileAndIdNot(model.getMobile(), model.getId());
        }
        if (existsMobile) {
            throw ExceptionHolder.serviceException(E1000000003, model.getMobile());
        }
        // 校验账号，唯一
        String username = model.getUsername();
        boolean existsUsername;
        if (StringUtils.isNotBlank(username)) {
            if (model.isNew()) {
                existsUsername = userRepository.existsByUsername(username);
            } else {
                existsUsername = userRepository.existsByUsernameAndIdNot(username, model.getId());
            }
            if (existsUsername) {
                throw ExceptionHolder.serviceException(E1000000003, username);
            }
        }
        // 校验邮箱，唯一
        String email = model.getEmail();
        boolean existsEmail;
        if (StringUtils.isNotBlank(email)) {
            if (model.isNew()) {
                existsEmail = userRepository.existsByEmail(email);
            } else {
                existsEmail = userRepository.existsByEmailAndIdNot(email, model.getId());
            }
            if (existsEmail) {
                throw ExceptionHolder.serviceException(E1000000003, email);
            }
        }

        return userRepository.save(model);
    }

    public void delete(UUID id) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> ExceptionHolder.serviceException(E1000000001, "用户-" + id));
        user.setStatus(UserStatus.DELETED);
        userRepository.save(user);
    }

}
